# -*- coding: utf-8 -*-
#
# Copyright 2009 Vanderbilt University
# 
# Licensed under the Apache License, Version 2.0 (the "License"); 
# you may not use this file except in compliance with the License. 
# You may obtain a copy of the License at 
# 
#     http://www.apache.org/licenses/LICENSE-2.0 
# 
# Unless required by applicable law or agreed to in writing, software 
# distributed under the License is distributed on an "AS IS" BASIS, 
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
# See the License for the specific language governing permissions and 
# limitations under the License. 

"""

.. moduleauthor:: John Paulett <john.paulett -at- vanderbilt.edu>
"""
import logging
import networkx as net
import pylab

import hornet
from hornet.plugin import Plugin

logger = logging.getLogger(__name__)

class NetworkPlotter(Plugin):
    def notify(self, event):
        for period, graph in event.data.iteritems():
            logger.debug('Drawing graph for %s' % period)
            pylab.figure(figsize=(18, 12), dpi=300, edgecolor='w')
            pos = net.pygraphviz_layout(graph, prog='fdp')
            #pos = net.shell_layout(graph)
            net.draw(graph, pos, alpha=0.15, width=0.05, node_size=1, 
                     node_color='k', arrows=False, font_size=10,
                     labels=self.biggest_nodes(graph, 20))
            pylab.savefig('../results/network_%s_%s.png' % (event.caller, period))
            #net.write_dot(graph, '../results/network_%s_%s.dot' % (event.caller, period))

            #FIXME premature end
            break
    
    def biggest_nodes(self, graph, num):
        nodes = sorted(graph.nodes(), reverse=True, 
                       key=lambda n: len(graph[n]))
        retval = {}
        for node in nodes[0:num]:
            retval[node] = str(node.id)
        return retval
